package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.config.minio.MinioProperties;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;

    @Override
    public String fileUpload(MultipartFile file) throws Exception {
        //处理文件名字
        String dateString = DateUtil.formatDate(new Date(), "yyyy/MM/dd");
        String fileName = dateString + "/" + UUID.randomUUID().toString().replaceAll("-", "")
                + file.getOriginalFilename();

        // -1表示不分批转换
        minioClient.putObject(
                PutObjectArgs.builder().bucket(minioProperties.getBucket())
                        .object(fileName)
                        .stream(file.getInputStream(), file.getSize(), -1L)
                        .contentType(file.getContentType())
                        .build());
        return minioProperties.getEndpoint() + "/" + minioProperties.getBucket() + "/" + fileName;

    }
}
